import { defineConfig, loadEnv, ConfigEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
import * as path from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig((mode: ConfigEnv) => {
  const url = loadEnv(mode.mode, `${process.cwd()}/env`).VITE_APP_INTERFACE_URL
  return {
    resolve: {
      //设置别名
      alias: {
        '@': path.resolve(__dirname, 'src')
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@use "@/assets/scss/global.scss"as *;'
        }
      }
    },
    plugins: [
      vue(),
      VueSetupExtend(),
      AutoImport({
        resolvers: [ElementPlusResolver()],
        dts: path.resolve(__dirname, 'src/types/auto-import.d.ts')
      }),
      Components({
        resolvers: [ElementPlusResolver()],
        dts: path.resolve(__dirname, 'src/types/components.d.ts')
      })
    ],
    server: {
      open: true,
      port: 8080, //启动端口
      host: '0.0.0.0',
      hmr: true,
      cors: true,
      // 设置 https 代理
      proxy: {
        '/api': {
          target: url,
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    build: {
      chunkSizeWarningLimit: 1600,
      rollupOptions: {
        output: {
          manualChunks(id) {
            // 将pinia的全局库实例打包进vendor，避免和页面一起打包造成资源重复引入
            if (id.includes(path.resolve(__dirname, 'src/store/index.ts'))) {
              return 'vendor'
            }
          }
        }
      }
    },
    logLevel: 'warn',
    envDir: 'env'
  }
})
